package com.util;

import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import java.util.*;
import java.text.*;

public class GuGuaUtil{

    public static void main(String []args){
        String mid="testaccount";
        String key="00112233445566778899AABBCCDDEEFF";

        Date date = new Date();
        String dateString = new SimpleDateFormat("yyyyMMddHHmmss").format(date);
        ArrayList s=new ArrayList();
        s.add("100.00");
        s.add("RON");
        s.add(Long.toString(date.getTime()));
        s.add("Order " + Long.toString(date.getTime()));
        s.add(mid);
        s.add(dateString);
        s.add(nonceGen(32));
        s.add(fp_hash(s,key));
    }

    public static String nonceGen(int len){
        String AlphaNumericString = "ABCDEF0123456789";
        StringBuilder sb = new StringBuilder(len);
        for (int i = 0; i < len; i++) {
            int index = (int)(AlphaNumericString.length() * Math.random());
            sb.append(AlphaNumericString.charAt(index));
        }
        return sb.toString();
    }

    //接口1 生成0x16, 0xB9, 0x16, 0x37, 0xE2, 0x29, 0x57, 0x3F, 0xAE, 0xF2, 0x2F, 0x32, 0x04, 0x83, 0x28, 0x3F, 0x68, 0x95, 0x4B, 0x83 字符串
    public static byte[] hex2byte(String key){
        int len = key.length();
        byte[] bkey = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            bkey[i / 2] = (byte) ((Character.digit(key.charAt(i), 16) << 4) + Character.digit(key.charAt(i+1), 16));
        }
        return bkey;
    }

    //RFC2104HMAC  接口2 生成fp_hash
    public static String fp_hash(ArrayList s, String key){
        StringBuffer ret = new StringBuffer();
        Formatter formatter = new Formatter();
        String t;
        Integer l;
        for(int i = 0; i < s.size(); i++)
        {
            t = s.get(i).toString().trim();
            if(t.length() == 0)
                ret.append("-");
            else
            {
                l = t.length();
                ret.append(l.toString());
                ret.append(t.toString());
            }
        }
        String data=ret.toString();
        try
        {
            SecretKeySpec secretKeySpec = new SecretKeySpec(hex2byte(key), "HmacMD5");
            Mac mac = Mac.getInstance("HmacMD5");
            mac.init(secretKeySpec);
            for (byte b : mac.doFinal(data.getBytes())) {
                formatter.format("%02x", b);
            }
        }
        catch(InvalidKeyException e){}
        catch (NoSuchAlgorithmException e) {}

        return formatter.toString().toUpperCase();
    }
}
